/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package compilador.analisadorSintatico;

import compilador.analisadorLexico.Token;
import compilador.analisadorLexico.TokenClass;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author Thiago
 */
public class TokenReader {
    
    private static final boolean DEBUG = false;

    private List<Token> tokens;

    private int index = 0;
    
    private static TokenReader instance = null;
    public static TokenReader createInstance(List<Token> tokens){
        
        instance = new TokenReader(tokens, true);
        instance.index = 0;
        
        return instance;
    }
    
    public static TokenReader createInstance(List<Token> tokens, boolean removeComment){
        
        instance = new TokenReader(tokens, removeComment);
        instance.index = 0;
        
        return instance;
    }

    public static TokenReader getInstance(){
        if(instance == null){
            instance = new TokenReader(new ArrayList<Token>(), true);
        }

        return instance;
    }

    private TokenReader(List<Token> ts, boolean removeComment) {
        this.tokens = new ArrayList<Token>(ts);
        
        if(removeComment){
            
            for(int i = 0; i < this.tokens.size();){
                Token t = tokens.get(i);
                if(t.getTokenClass().equals(TokenClass.COMENTARIO)){
                    tokens.remove(i);
                    
                    if(TokenReader.DEBUG)
                        System.out.println("Removido! " + t);
                    
                }else{
                     i++;
                }
            }
            if(TokenReader.DEBUG){
                for(Token t : tokens){
                    System.out.println(t);
                }
            }
        }
        
    }

    public boolean hasToken(){
        return index < tokens.size();
    }
    
    public Token consome(){
        Token t = get(index);
        index ++;

        return t;
    }

    public Token seeNext(){
        Token t = this.get(index + 1);
        return t;
    }

    /*
     * exibe o token que está a skip posições do atual
     * quando skip = 1 equivale a seeNext()
     */  
    public Token seeNext(int skip){
        Token t = this.get(index + skip);
        return t;
    }
    
    public Token seeCurrent(){
        Token t = this.get(index);
        return t;
    }

    private Token get(int i) {
        Token t = null;
        final int size = tokens.size();

        if(i < size)
            t = tokens.get(i);
        else{
            if(size > 0){
                t = new Token(TokenClass.PALAVRA_RESERVADA, "endOfFile", tokens.get(size-1).getLinha());
            }
            else{
                t = new Token(TokenClass.PALAVRA_RESERVADA, "endOfFile", 0);
            }
        }

        return t;
    }

    public List<Token> getTokens() {
        return tokens;
    }
}
